import { observable, action, autorun, toJS } from 'mobx';
import { WeaLocaleProvider } from 'ecCom';
import {WeaForm, WeaTableNew} from 'comsMobx'
import { message, Button, Modal } from "antd";
import * as Apis from '../../apis/info';
import { feedbackDialogStore } from '../dialog/feedbackDialogStore';
import {Text} from '../../components/util/text';
const text = new Text();

const {TableStore} = WeaTableNew;
const getLabel = WeaLocaleProvider.getLabel;
export default class infoReportStore {

    @observable feedbackDialogStore = new feedbackDialogStore(this);

    @observable infoForm = new WeaForm();    //新建上报信息表单
    @observable condition = [];    //新建上报condition

    @observable responseData = {};
    @observable selectTabKey = "basicInfo";    //页签默认选中
    @observable tableStore = new TableStore();  //反馈信息页签中反馈信息列表

    @observable isRight = false;        //判断是否有权限
    @observable loadingSpin = true;     //全局loading

    @observable buttonDisabled = false;  //操作按钮的状态
    curids = [];        //当前操作的上报信息id   1.新建上报时选择多个路径产生多条   2.列表中点击标题为一条
    showTab = false;   //是否展示反馈信息该页签，默认为false
    pathIds = [];
    by = "";
    constructor() {
    }

    @observable status = {
        loading: false,
    }

    setState = (params = {}) => {
        Object.keys(params).forEach(o => {
            this.status[o] = params[o];
        })
        return this;
    }

    /**
     * 初始化表单
     */
    @action
    initInfoForm = (params = {}) => {
        this.by = params.by;
        this.status.loading = true;
        this.loadingSpin = true;
        this.infoForm = new WeaForm();
        this.condition = [];
        Apis.getInfoCondition(params).then(data => {
            if (data.api_status == '1') {
                this.status.loading = false;
                this.loadingSpin = false;
                this.isRight = data.isRight;
                if (!this.isRight) {
                    return;
                }
                if (data.type == "showTab") {
                    this.showTab = true;
                } else {
                    this.showTab = false;
                }
                this.pathIds = data.pathIds;
                this.condition = data.infoConditionGroup;
                this.infoForm = new WeaForm();
                this.infoForm && !this.infoForm.isFormInit && this.infoForm.initFormFields(this.condition);
                this.responseData = { rightMenus: data.rightMenus };
            } else {
                message.error(data.api_errormsg);
            }

        })
    }


    @action
    reLoad = () => {
        this.tableStore.getDatas(this.tableStore.dataKey, this.tableStore.current, this.tableStore.pageSize, this.tableStore.sortParams)
    }

    getRightMenu = () => {
        const { rightMenus } = this.responseData;
        let btnArr = [];
        rightMenus && rightMenus.length > 0 && rightMenus.map(m => {
            btnArr.push({
                key: m.type,
                icon: <i className={m.menuIcon} />,
                content: m.menuName,
                onClick: key => {
                    this.buttonClick(key);
                },
                disabled: m.type == 'BTN_SAVE' && this.buttonDisabled === true
            })

        });
        return btnArr;
    }
    /**
   * 上方按钮
   */
    getTopButton = () => {
        const { rightMenus } = this.responseData;
        let btnArr = [];
        rightMenus && rightMenus.length > 0 && rightMenus.map((m,index) => {
            btnArr.push(
                <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@ymw0aq@${index}`} style={{ marginLeft: "10px" }} type={"primary"}
                    disabled={ (m.type == 'BTN_SAVE' || m.type == 'BTN_EDIT_SAVE' || m.type == 'BTN_APPSUBMIT') && this.buttonDisabled === true}
                    onClick={() => {
                        this.buttonClick(m.type);
                    } }>
                    {m.menuName}
                </Button>
            );
        });
        return btnArr;
    }

    //得到信息反馈List
    @action
    getInfoFeedbackList = (params = {}) => {
        Apis.getInfoFeedbackList({...params}).then(data => {
            this.tableStore.getDatas(data.sessionkey, 1)
        })
}

buttonClick(key) {
    if (key == "BTN_SAVE") {            //新建时的保存
        this.saveReportForm({ type: 'save' });
    }
    if (key == "BTN_EDIT") {             //编辑
        if (this.selectTabKey != "basicInfo") {
            this.changeTab("basicInfo");
        }
        this.initInfoForm({ type: 'edit', ids:this.curids.join(",") });
    }
    if (key == "BTN_EDIT_SAVE") {       //编辑时的保存
        this.saveReportForm({ type: 'update' });
    }
    if (key == "BTN_APPSUBMIT") {       //正式提交
        const _this = this;
        Modal.confirm({
            content: text.SURESUBMITAUDIT,
            onOk() {
                _this.saveReportForm({ type: 'submit' });
            },
            onCancel() { },
        });
    }
    if (key == "BTN_PASS") {        //审批时的审批通过按钮
        const _this = this;
        Modal.confirm({
            content: text.SUREAUDIT,
            onOk() {
                Apis.passInfoReport({ id: _this.curids.join(",") }).then(data => {
                    if (data.api_status == '1') {
                        if (!data.isRight) {
                            message.error(getLabel(2012, '对不起，您暂时没有权限！'));
                            return;
                        }
                        window.close();   //关闭当前详情页
                        window.opener._table.reLoad();
                    } else {
                        message.error(data.api_errormsg);
                    }
                });
            },
            onCancel() { },
        });
    }
    if (key == "BTN_RETURN") {        //审批时的驳回按钮
        this.feedbackDialogStore.initFeedbackForm({ id: this.curids.join(","), typeNum: 0 });
        //this.feedbackDialogStore.setState({ visible: true });
    }
    if(key == 'BTN_ASSIST_SAVE') {          //待报时的保存按钮
        this.saveReportForm({ type: 'assistSave' });
    }
}
//保存上报信息
@action
saveReportForm = (flag) => {
    let formParams = this.infoForm.getFormParams();
    let params = {...formParams };
    let checkPath = false;
    //判断当前用户是否已选择报送单位  checkPath   
    if(flag.type != 'assistSave') {
        for (var i in params) {
        this.pathIds.map(c => {
            if (i == c) {
                if (params[i][0] == "1") {
                    checkPath = true;
                }
            }
        });
        }
        if(!checkPath) {
            message.warn(text.TIP1);
            return ;
        }
    }
    // if(params.reportType == '1' && params.atach == '') {
    //     message.warn(`${getLabel(123, '专报时请上传附件')}`);
    //     return ;
    // }
        
    this.infoForm.validateForm().then(f => {
        if (f.isValid ) {
                 if (flag.type == "save") {
					let _this = this;
                    let newParams = {...params, 'pathIds': this.pathIds };
					Modal.confirm({
						title: text.DOSURE,
						content: '保存后当前路径不可修改，是否确认?',
						onOk() {
                            _this.buttonDisabled = true;
							Apis.saveInfoReport(newParams).then(data => {
                                _this.buttonDisabled = false;
								if (data.api_status == '1') {
                                    if (!data.isRight) {
                                        message.error(getLabel(2012, '对不起，您暂时没有权限！'));
                                        return;
                                    }
									if(typeof(data.msg) != 'undefined') {
                                        //_this.showTip = true;
                                        _this.infoForm.showError('title', data.msg);
										return ;
									}
									message.success(text.SAVESUCCESS);
									_this.curids = data.ids;
									_this.initInfoForm({ ids:_this.curids.join(","), type: 'show', });
								} else {
									message.error(data.api_errormsg);
								}
							});
						},
						onCancel() {},
					})
                    
                }else if(flag.type=='assistSave'){
                     let newParams = {...params,'pathIds': this.pathIds};
                    Apis.saveInfoReport(newParams).then(data => {
                        if (data.api_status == '1') {
                            if (!data.isRight) {
                                message.error(getLabel(2012, '对不起，您暂时没有权限！'));
                                return;
                            }
                            if(typeof(data.msg) != 'undefined') {
                                 this.infoForm.showError('title', data.msg);
                                return ;
                            }
                            message.success(text.SAVESUCCESS);
                            this.curids = data.ids;
                            this.initInfoForm({ ids:this.curids.join(","), type: 'show',by:'assistReport' });
                            window.opener._table.reLoad();
                        } else {
                            message.error(data.api_errormsg);
                        }
                    });
                }
                else if (flag.type == "update") {
                    let newParams = {...params, 'pathIds': this.pathIds, ids: this.curids, 'type': '1' };
                    this.buttonDisabled = true;
                    Apis.saveInfoReport(newParams).then(data => {
                        this.buttonDisabled = false;
                        if (data.api_status == '1') {
                            if (!data.isRight) {
                                message.error(getLabel(2012, '对不起，您暂时没有权限！'));
                                return;
                            }
                            if (typeof (data.msg) != 'undefined') {
                                this.infoForm.showError('title', data.msg);
                                return;
                            }
                            message.success(text.SAVESUCCESS);
                            this.initInfoForm({ ids: this.curids.join(","), type: 'show', });
                        } else {
                            message.error(data.api_errormsg);
                        }
                    });
                    //  Apis.updateInfoReport(newParams).then(data => {
                    //     if (data.api_status == '1') {
                    //         message.success(`${getLabel(18758, '保存成功')}`);
                    //         this.initInfoForm({ id:this.curid,ids: this.curids, type: 'show', });
                    //     } else {
                    //         message.error(data.api_errormsg);
                    //     }
                    //  });
                } else if (flag.type == "submit") {
                    // Apis.submitInfoReport({...params,'pathIds':this.pathIds, id:this.curid,ids:this.curids}).then(data => {
                    this.buttonDisabled = true;
                    Apis.submitInfoReport({ ids: this.curids.join(",") }).then(data => {
                        this.buttonDisabled = false;
                        if (data.api_status == '1') {
                            if (!data.isRight) {
                                message.error(getLabel(2012, '对不起，您暂时没有权限！'));
                                return;
                            }
                            message.success(text.SUBMITAUDIT);

                            //window.open("/spa/workflow/index_form.jsp#/main/workflow/req?iscreate=1&requestid="+data.newrequestid+"&workflowid="+data.flowid);

                            if (this.by == 'list') {
                                window.close();             //关闭弹出的窗口，父窗口列表刷新
                                if (window.opener && window.opener._table && window.opener._table.reLoad) {
                                    window.opener._table.reLoad();
                                }
                            } else {
                                this.initInfoForm();
                            }
                        } else {
                            message.error(data.api_errormsg);
                        }
                    });
                }
            } else {
                f.showErrors();
            }
        });
    }

    //设置选中按钮
    changeTab = (key) => {
	   this.selectTabKey = key;
	   if (key == "basicInfo") {              //基本信息
	   } else if (key == "infoFeedback") {     //信息反馈
        this.getInfoFeedbackList({ infoId: this.curids.join(","), by: 'tab' });    //by表示点击页签显示的反馈信息
	   }
    }

    formChange = (value) => {
        const params = this.infoForm.getFormDatas();
        let c = this.condition;
        this.infoForm = new WeaForm();
        c.map(cd => {
            cd.items.map((item, index) => {
                if (item.domkey[0] == 'atach') {
                    if(value == '1') {
                        cd.items[index].viewAttr = 3;
                        cd.items[index].rules = 'required';
                    } else {
                        cd.items[index].viewAttr = 2;
                        delete cd.items[index].rules;
                    }
                    
                }
                //判断路径是否开启专报，根据json中的specialReport来判断
                if(item.conditionType == 'CASCADER') {
                    if(value == '1' && item.compDef.specialReport == false) {
                        // if(this.by == 'assistReport') {
                        //     item.compDef.value = '0';
                        // }
                        item.compDef.viewAttr = 1;
                        let domkey = item.domkey[0];
                        params[domkey] = new Array(['0']);
                        
                    } else if (value == '0' && item.compDef.specialReport == false) {
                        // if(this.by == 'assistReport') {
                        //     item.compDef.value = '1';
                        //     item.compDef.viewAttr = 1;
                        //     let domkey = item.domkey[0];
                        //     params[domkey] = new Array(['1']);
                        // } else {
                            item.compDef.viewAttr = 2;
                            let domkey = item.domkey[0];
                            params[domkey] = new Array(['0']);
                        //}
                    }
                }
            });
        })
        this.infoForm.initFormFields(c);
        this.infoForm.updateFields({...params},true);
    }
}